package com.itheima.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request) {
        String phone = user.getPhone();
        String code = RandomUtil.randomString(4);
        log.info("验证码为：{}", code);
        request.getSession().setAttribute(phone, code);
        return R.success("手机验证码发送成功");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map user, HttpSession session) {
        String phone = (String) user.get("phone");
        String code = (String) user.get("code");
        String sessionAttribute = (String) session.getAttribute(phone);
        if (sessionAttribute.equals(code)) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User one = userService.getOne(queryWrapper);
            if (one != null) {
                session.setAttribute("user", one.getId());
                return R.success(one);
            } else {
                User newUser = new User();
                newUser.setPhone(phone);
                userService.save(newUser);
                session.setAttribute("user", newUser.getId());
                return R.success(newUser);
            }
        }
        return R.error("登录失败");
    }
}
